package cn.com.flever.component;

import cn.com.flever.action.AutoDeployAction;
import cn.com.flever.entity.Sym3Config;
import cn.com.flever.utils.ConsoleUtils;
import cn.com.flever.utils.Sym3Utils;
import com.intellij.execution.ExecutionManager;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.filters.TextConsoleBuilder;
import com.intellij.execution.filters.TextConsoleBuilderFactory;
import com.intellij.execution.impl.ConsoleViewImpl;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.notification.*;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.search.GlobalSearchScope;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.jetbrains.annotations.SystemIndependent;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import static java.lang.Runtime.getRuntime;

public class AutoDeployDialog extends JDialog {
    private static final String fileSeparator = System.getProperty("file.separator");
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextField textField1;
    private JTextField textField2;
    private JButton deployButton;
    private JTextField a22TextField;
    private static final String token="";
    private Project project;
    private ScheduledThreadPoolExecutor poolExecutor=new ScheduledThreadPoolExecutor(1);
    public static AtomicInteger tryTime=new AtomicInteger(0);
    public static HashMap<String,String> tagMap=new HashMap<>();
    

    public AutoDeployDialog(Project project) {

        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);
        this.project=project;

        /*读取输入框中的token配置，如果不存在则使用默认的token*/

        buttonOK.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    onOK(false);
                } catch (Exception ioException) {
                    ioException.printStackTrace();
                }
            }
        });

        deployButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    FileUtils.writeStringToFile(new File(AutoDeployAction.cookieFilePath),a22TextField.getText(),"UTF-8");
                    onDeploy();
                } catch (Exception ioException) {
                    ioException.printStackTrace();
                }
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    private void onOK(boolean isDeploy) throws Exception {
        /*获取项目根路径，*/
        String basePath = this.project.getBasePath();

        /*复制脚本文件到当前项目路径*/
        /*复制脚本文件到当前项目路径*/
        String scriptPath = this.getClass().getClassLoader().getResource("META-INF/script/").getPath();
        File scriptFloder=new File(scriptPath);
        List scriptFile = CollectionUtils.arrayToList(scriptFloder.listFiles());
        //FileUtils.copyToDirectory((Iterable<File>)scriptFile.iterator(),new File(basePath));
        scriptPath=scriptPath.replace("file:/","");
        scriptPath=scriptPath.replace("!/META-INF/script/","");
        accessJarFile(scriptPath,"META-INF/script/",basePath);

        /*执行脚本，自动发布tag*/
        String version=textField1.getText();
        if(StringUtils.isEmpty(version))
        {
            version="v-sym3-0.0.1-alpha.001";
            textField1.setText(version);
            AutoDeployDialog.tagMap.put(this.project.getName(),version);
        }
        else{
            AutoDeployDialog.tagMap.put(this.project.getName(),textField1.getText());
        }
        String message=textField2.getText();
        if(StringUtils.isEmpty(message))
        {
            message="auto deploy commit";
            textField2.setText(message);
        }
        if(!isDeploy)
        {
            String cmd="cmd /c start "+basePath+fileSeparator+"update-sym3tags.exe "+project.getName()+" "+version+" \""+message+"\"";
            Process process = Runtime.getRuntime().exec(cmd,null,new File(basePath));
            Sym3Utils.updateApplication(this.project.getName(),this.textField1.getText(),this.a22TextField.getText());
        }
        else {
            String cmd="cmd /c start "+basePath+fileSeparator+"make-sym3tags.exe "+project.getName()+" "+version+" \""+message+"\"";
            Process process = Runtime.getRuntime().exec(cmd,null,new File(basePath));
        }
        /*开启定时任务，不断的去尝试删除容器中错误的pod，直到pod正常*/
        String projectName=this.project.getName();
        String cookie=this.a22TextField.getText();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                boolean status = Sym3Utils.queryApplicationStatus(projectName, cookie);
                if (!status&& tryTime.incrementAndGet()<10) {
                    poolExecutor.schedule(this,1,TimeUnit.MINUTES);
                }
                if(status)
                {
                    NotificationGroup notificationGroup = new NotificationGroup("notificationGroup", NotificationDisplayType.BALLOON, true);
                    Notification notification = notificationGroup.createNotification("测试环境自动部署完成", NotificationType.INFORMATION);
                    Notifications.Bus.notify(notification);
                }
                else{
                    NotificationGroup notificationGroup = new NotificationGroup("notificationGroup", NotificationDisplayType.BALLOON, true);
                    Notification notification = notificationGroup.createNotification("第"+tryTime.get()+"次检测，容器未部署成功", NotificationType.INFORMATION);
                    Notifications.Bus.notify(notification);
                }
            }
        };
        poolExecutor.schedule(runnable,1,TimeUnit.MINUTES);
        dispose();
    }

    /**
     * 自动部署事件
     * @throws Exception
     */
    private void onDeploy()throws Exception{
        if(StringUtils.isEmpty(this.textField1.getText()))
        {
            Messages.showErrorDialog(
                    project,
                    "tag不可为空",
                    "测试环境部署异常");
            return;
        }
        if(StringUtils.isEmpty(this.a22TextField.getText()))
        {
            Messages.showErrorDialog(
                    project,
                    "cookie不可为空，可从sym3中的任意请求中复制cookie",
                    "测试环境部署异常");
            return;
        }
        onOK(true);
        Sym3Utils.createService(this.project.getName(),this.a22TextField.getText());
        Sym3Utils.createCofnig(this.project.getName(),this.a22TextField.getText());
        Sym3Utils.createApplication(this.project.getName(),this.textField1.getText(),this.a22TextField.getText());
        Messages.showInfoMessage(
                project,
                "操作完成，是否成功请看sym3",
                "测试环境部署异常");
        dispose();
    }

    private void onCancel() {
        // add your code here if necessary
        dispose();
    }


    /**
     * 解压缩jar中的脚本文件
     * @param jarFilePath jar包路径
     * @param fileName 脚本文件夹目录
     * @param toDir 项目根路径
     * @throws Exception
     */
    public void accessJarFile(String jarFilePath,String fileName, String toDir) throws Exception{
        JarFile myJarFile = new JarFile(jarFilePath);
        Enumeration myEnum = myJarFile.entries();
        while(myEnum.hasMoreElements()){
            JarEntry myJarEntry = (JarEntry)myEnum.nextElement();
            if(myJarEntry.getName().startsWith(fileName)&&(!myJarEntry.isDirectory())){
                InputStream is = myJarFile.getInputStream(myJarEntry);
                String name = myJarEntry.getName();
                name=name.replace(fileName,"");
                File scriptFloder=new File(toDir+fileSeparator+name);
                if(!scriptFloder.exists())
                {
                    scriptFloder.createNewFile();
                }
                FileUtils.copyInputStreamToFile(is,scriptFloder);
            } else{
                continue;
            }
        }
        myJarFile.close();
    }

    public JTextField getTextField1() {
        return textField1;
    }

    public JTextField getTextField2() {
        return textField2;
    }

    public JTextField getA22TextField() {
        return a22TextField;
    }
}
